<script setup lang="js">
import { getMonthlyTrafficData } from "@@/apis/trafficReport"
import { Document, Download, View } from "@element-plus/icons-vue"
import { reactive } from "vue"
import { useTable } from "@/hooks/useTable"

// 解构useTable返回的属性和方法，使模板更加简洁
const {
  tableData,
  loading,
  pagination,
  searchForm,
  showSearchForm,
  toggleSearchForm,
  handleSearch,
  handleReset,
  handleSizeChange,
  handleCurrentChange,
  exportData
} = useTable({
  // 简化API配置
  api: {
    // 获取列表数据
    getList: async (params) => {
      return await getMonthlyTrafficData(params)
    },
    // 导出数据
    export: async (params) => {
      // 调用API并设置responseType为blob以获取文件流
      return await getMonthlyTrafficData(params, { responseType: "blob" })
    }
  },
  // 分页配置
  pagination: { pageSize: 10 },
  // 搜索参数初始值
  searchParams: { searchDate: "" },
  // 是否在组件挂载时立即加载数据
  immediateLoad: true
})

// 表格列配置
const columns = reactive([
  { type: "index", label: "序号", width: 80, align: "center" },
  { prop: "date", label: "日期", minWidth: 120 },
  { prop: "total", label: "过江总量", minWidth: 120, formatter: "formatNumber" },
  { prop: "avgSpeed", label: "平均时速(km/h)", minWidth: 140 },
  { prop: "changeRate", label: "同比", minWidth: 100, formatter: "formatChangeRate" },
  { prop: "largeVehicles", label: "大型车合计", width: 120, formatter: "formatNumber" },
  { prop: "smallVehicles", label: "小型车合计", width: 120, formatter: "formatNumber" },
  { prop: "urbanLarge", label: "市内大型车", width: 120, formatter: "formatNumber" },
  { prop: "urbanSmall", label: "市内小型车", width: 120, formatter: "formatNumber" },
  { prop: "urbanTotal", label: "市内合计", width: 120, formatter: "formatNumber" },
  { prop: "suburbanLarge", label: "市外大型车", width: 120, formatter: "formatNumber" },
  { prop: "suburbanSmall", label: "市外小型车", width: 120, formatter: "formatNumber" },
  { prop: "suburbanTotal", label: "市外合计", width: 120, formatter: "formatNumber" }
])

// 导出数据的封装函数，增加友好的错误提示
function handleExport() {
  return exportData().catch((error) => {
    console.error("导出失败:", error)
    // 确保loading状态重置为false
    loading.value = false
    // 这里可以添加UI提示，如Element Plus的Message组件
    // ElMessage.error('导出数据失败，请稍后重试')
  })
}

// 格式化数字
function formatNumber(num) {
  if (num === null || num === undefined || num === "") {
    return num
  }
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",")
}
</script>

<template>
  <div class="report-wrapper">
    <!-- 搜索表单 -->
    <el-form v-if="showSearchForm" :model="searchForm" class="search-form">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-form-item label="时间">
            <el-date-picker
              v-model="searchForm.searchDate" type="date" placeholder="选择日期" clearable format="YYYY-MM-DD"
              value-format="YYYY-MM-DD" style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" align="center">
          <el-form-item>
            <el-button type="primary" @click="handleSearch" style="margin-right: 10px">
              查询
            </el-button>
            <el-button @click="handleReset">
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="report-content">
      <!-- 表格头部 -->
      <div class="table-header">
        <h3><el-icon><Document /></el-icon>全市在途车辆统计</h3>
        <div class="header-actions">
          <el-button class="export-btn" type="primary" @click="handleExport">
            <el-icon><Download /></el-icon> 导出
          </el-button>
          <el-button @click="toggleSearchForm">
            <el-icon><View /></el-icon> 
            {{ showSearchForm ? '隐藏' : '显示' }}查询
          </el-button>
        </div>
      </div>

      <!-- 表格 -->
      <el-table v-loading="loading" :data="tableData" style="width: 100%" border>
        <template v-for="column in columns" :key="column.prop || column.type">
          <el-table-column
            v-if="column.formatter" v-bind="column" :prop="column.prop" :label="column.label"
            :width="column.width" :min-width="column.minWidth" :align="column.align" :type="column.type"
          >
            <template #default="{ row }">
              <template v-if="column.formatter === 'formatNumber'">
                {{ formatNumber(row[column.prop]) }}
              </template>
              <template v-else-if="column.formatter === 'formatChangeRate'">
                <span class="change-rate-down">{{ row[column.prop] }}</span>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            v-else v-bind="column" :prop="column.prop" :label="column.label" :width="column.width"
            :min-width="column.minWidth" :align="column.align" :type="column.type"
          />
        </template>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :page-sizes="pagination.pageSizes" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.report-wrapper {
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.report-content {
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
}

// 搜索表单样式
.search-form {
  margin-bottom: 16px;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;

  .el-form-item {
    // margin-bottom: 0;
  }
}

// 表格头部样式
.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.table-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
  color: #1890ff;
}

.header-actions {
  display: flex;
  gap: 10px;
}

// 自定义同比样式
.change-rate-down {
  color: #f5222d;
}

// 导出按钮样式
.export-btn {
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
}

// 表格行悬停样式
:deep(.el-table__row) {
  transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);

  &:hover {
    background-color: #f5f7fa;
  }
}

// 表头样式
:deep(.el-table__header-wrapper th) {
  background: #f0f4f9 !important;
  color: #606266 !important;
  font-weight: 500 !important;
}

// 分页容器样式
.pagination-container {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

// 表格体滚动条样式
:deep(.el-table__body-wrapper) {
  overflow-x: auto;
}
</style>
